<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单 - 用户端</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
            font-family: 'Roboto', sans-serif;
            min-height: 100vh;
            margin: 0;
        }
        .layout {
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 210px;
            background: #fff;
            box-shadow: 2px 0 16px rgba(0,0,0,0.07);
            display: flex;
            flex-direction: column;
            padding: 32px 0 0 0;
        }
        .sidebar-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2d3a4b;
            text-align: center;
            margin-bottom: 36px;
        }
        .nav {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .nav a {
            display: block;
            padding: 12px 32px;
            color: #4a5a6a;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .nav a.active, .nav a:hover {
            background: #eaf3ff;
            color: #3478f6;
            border-left: 4px solid #7eb6ff;
        }
        .logout-btn {
            margin: 32px 24px 0 24px;
            padding: 12px 0;
            width: calc(100% - 48px);
            background: linear-gradient(90deg, #ff6b6b 0%, #ffb36b 100%);
            color: #fff;
            font-weight: 700;
            border: none;
            border-radius: 8px;
            font-size: 1.08rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .logout-btn:hover {
            background: linear-gradient(90deg, #ffb36b 0%, #ff6b6b 100%);
        }
        .content {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            min-height: 100vh;
            padding: 48px 32px;
        }
        .container {
            background: #fff;
            padding: 36px 28px 28px 28px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            width: 1100px;
            max-width: calc(100vw - 210px - 64px);
        }
        .title {
            font-size: 1.7rem;
            font-weight: 700;
            color: #2d3a4b;
            margin-bottom: 24px;
            text-align: center;
        }
        .search-section {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 24px;
            gap: 16px;
        }
        .search-input {
            padding: 8px 12px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            font-size: 0.95rem;
            outline: none;
            transition: border 0.2s;
            width: 220px;
        }
        .search-input:focus {
            border-color: #7eb6ff;
        }
        .search-btn, .reset-btn {
            padding: 8px 16px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            background: #fff;
            color: #4a5a6a;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .search-btn:hover, .reset-btn:hover {
            background: #f5f8fa;
            border-color: #7eb6ff;
        }
        .table-container {
            max-height: calc(100vh - 300px);
            overflow-y: auto;
            border: 1px solid #e3e8ee;
            border-radius: 8px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 8px;
            border-bottom: 1px solid #e3e8ee;
            text-align: center;
        }
        th {
            background: #f5f8fa;
            color: #4a5a6a;
            font-weight: 700;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .book-title {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: help;
        }
        .status-pending {
            color: #ff6b6b;
            font-weight: 600;
        }
        .status-shipped {
            color: #28a745;
            font-weight: 600;
        }
        .status-completed {
            color: #007bff;
            font-weight: 600;
        }
        .status-cancelled {
            color: #999;
            font-weight: 600;
            text-decoration: line-through;
        }
        .actions button {
            margin: 0 4px;
            padding: 6px 14px;
            border: none;
            border-radius: 6px;
            font-size: 0.98rem;
            cursor: pointer;
            color: #fff;
            background: #6dd47e;
            transition: background 0.2s;
        }
        .actions button.view:hover { background: #5bc06d; }
        .pagination {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 8px;
            margin-top: 18px;
            font-size: 15px;
        }
        .pagination button {
            padding: 6px 16px;
            border: none;
            border-radius: 4px;
            background: #f5f5f5;
            color: #3478f6;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
        }
        .pagination button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }
        .pagination .page-info {
            margin: 0 8px;
            color: #333;
        }
        .pagination select {
            margin: 0 4px;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid #d1d9e6;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }
        .error {
            color: #ff6b6b;
            text-align: center;
            padding: 20px;
        }
        /* 弹窗样式 */
        .modal-mask {
            position: fixed;
            left: 0; top: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.18);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .modal-card {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 12px 40px rgba(0,0,0,0.18);
            min-width: 420px;
            max-width: 98vw;
            padding: 38px 38px 28px 38px;
            position: relative;
            animation: fadeIn 0.2s;
        }
        .modal-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: #2d3a4b;
            margin-bottom: 12px;
            letter-spacing: 1px;
            text-align: center;
        }
        .modal-divider {
            width: 100%;
            height: 1px;
            background: #e3e8ee;
            margin-bottom: 22px;
            border: none;
        }
        .modal-close {
            position: absolute;
            right: 18px;
            top: 18px;
            font-size: 1.3rem;
            color: #aaa;
            background: none;
            border: none;
            cursor: pointer;
        }
        .modal-row {
            display: flex;
            align-items: flex-start;
            margin-bottom: 18px;
        }
        .modal-label {
            width: 110px;
            color: #888;
            font-weight: 500;
            text-align: right;
            flex-shrink: 0;
            margin-right: 10px;
            letter-spacing: 1px;
        }
        .modal-value {
            color: #222;
            word-break: break-all;
            text-align: left;
            flex: 1;
        }
        .modal-value strong {
            font-weight: 700;
        }
        .modal-status-tag {
            display: inline-block;
            padding: 2px 12px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 700;
            color: #fff;
            background: #ff6b6b;
        }
        .modal-status-tag.shipped { background: #28a745; }
        .modal-status-tag.completed { background: #007bff; }
        .modal-status-tag.cancelled { background: #999; }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
    <script type="module">
        import { API_BASE_URL } from './api_config.js';
        window.API_BASE_URL = API_BASE_URL;
    </script>
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="sidebar-title">用户中心</div>
            <nav class="nav">
                <a href="user_books.html">浏览书籍</a>
                <a href="user_orders.html" class="active">我的订单</a>
                <a href="user_profile.html">个人信息</a>
            </nav>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </aside>
        <main class="content">
            <div class="container">
                <div class="title">我的订单</div>
                <div class="search-section">
                    <input type="text" id="bookNameSearch" class="search-input" placeholder="搜索书名...">
                    <button id="searchBtn" class="search-btn">搜索</button>
                    <button id="resetBtn" class="reset-btn">重置</button>
                </div>
                <div class="table-container">
                    <table id="ordersTable">
                        <thead>
                            <tr>
                                <th>订单ID</th>
                                <th>书名</th>
                                <th>商家</th>
                                <th>数量</th>
                                <th>总价</th>
                                <th>状态</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody">
                            <!-- 动态生成订单数据 -->
                        </tbody>
                    </table>
                </div>
                <div id="loadingMessage" class="loading" style="display: none;">正在加载订单数据...</div>
                <div id="errorMessage" class="error" style="display: none;"></div>
                <div class="pagination" id="pagination" style="display: none;"></div>
            </div>
        </main>
    </div>
    <!-- 订单详情弹窗 -->
    <div class="modal-mask" id="orderModalMask">
        <div class="modal-card">
            <button class="modal-close" id="orderModalClose">×</button>
            <div class="modal-title">订单详情</div>
            <hr class="modal-divider" />
            <div id="orderModalContent">
                <!-- 动态填充 -->
            </div>
        </div>
    </div>
    <script>
    (function() {
        var apiBaseUrl = window.API_BASE_URL || 'http://localhost:3010';
        var currentPage = 1;
        var pageSize = 10;
        var totalPages = 0;
        var totalRecords = 0;
        var bookName = '';
        // 获取用户ID
        var userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        var buyerId = userInfo.userId;
        if (!buyerId) {
            alert('未检测到用户身份，请重新登录');
            window.location.href = 'login.html';
            return;
        }
        function loadOrders() {
            showLoading();
            const params = new URLSearchParams({
                pageNum: currentPage,
                pageSize: pageSize,
                buyerId: buyerId
            });
            if (bookName) params.append('bookName', bookName);
            fetch(`${apiBaseUrl}/bookOrder/userPage?${params}`)
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success && data.code === 200) {
                        displayOrders(data.data);
                        updatePagination(data.data);
                    } else {
                        showError('加载订单失败: ' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('网络错误，请检查网络连接');
                });
        }
        function displayOrders(data) {
            const tbody = document.getElementById('ordersTableBody');
            tbody.innerHTML = '';
            if (data.records && data.records.length > 0) {
                data.records.forEach(order => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${order.id}</td>
                        <td class="book-title" title="${order.bookTitle}">${order.bookTitle}</td>
                        <td>${order.merchantName || ''}</td>
                        <td>${order.quantity}</td>
                        <td>￥${order.totalPrice.toFixed(2)}</td>
                        <td class="status-${getStatusClass(order.status)}">${getStatusText(order.status)}</td>
                        <td>${formatDate(order.createdAt)}</td>
                        <td class="actions">
                            <button class="view" onclick="viewOrder(${order.id})">查看</button>
                            ${order.status === 0 ? '<button class="cancel" onclick="cancelOrder(' + order.id + ')">取消</button>' : ''}
                            ${order.status === 1 ? '<button class="sign" onclick="signOrder(' + order.id + ')">签收</button>' : ''}
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #666;">暂无订单数据</td></tr>';
            }
        }
        function getStatusClass(status) {
            switch (status) {
                case 0: return 'pending';
                case 1: return 'shipped';
                case 2: return 'completed';
                case 3: return 'cancelled';
                default: return 'pending';
            }
        }
        function getStatusText(status) {
            switch (status) {
                case 0: return '待发货';
                case 1: return '已发货';
                case 2: return '已完成';
                case 3: return '已取消';
                default: return '待发货';
            }
        }
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        function updatePagination(data) {
            const pagination = document.getElementById('pagination');
            totalPages = data.pages;
            totalRecords = data.total;
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            pagination.style.display = 'flex';
            pagination.innerHTML = '';
            // 上一页
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadOrders();
                }
            };
            pagination.appendChild(prevBtn);
            // 页码信息
            const pageInfo = document.createElement('span');
            pageInfo.className = 'page-info';
            pageInfo.textContent = `第 ${currentPage} / ${totalPages} 页`;
            pagination.appendChild(pageInfo);
            // 下一页
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    loadOrders();
                }
            };
            pagination.appendChild(nextBtn);
            // 每页显示
            const pageSizeLabel = document.createElement('span');
            pageSizeLabel.textContent = '每页显示:';
            pageSizeLabel.style.marginLeft = '12px';
            pagination.appendChild(pageSizeLabel);
            const pageSizeSelect = document.createElement('select');
            [5, 10, 15, 20, 50].forEach(size => {
                const option = document.createElement('option');
                option.value = size;
                option.textContent = size;
                if (size === pageSize) option.selected = true;
                pageSizeSelect.appendChild(option);
            });
            pageSizeSelect.onchange = function() {
                pageSize = parseInt(this.value);
                currentPage = 1;
                loadOrders();
            };
            pagination.appendChild(pageSizeSelect);
            const pageSizeUnit = document.createElement('span');
            pageSizeUnit.textContent = '条';
            pagination.appendChild(pageSizeUnit);
        }
        function showLoading() {
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('ordersTable').style.display = 'none';
            document.getElementById('pagination').style.display = 'none';
        }
        function hideLoading() {
            document.getElementById('loadingMessage').style.display = 'none';
            document.getElementById('ordersTable').style.display = 'table';
        }
        function showError(message) {
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorMessage').style.display = 'block';
            document.getElementById('ordersTable').style.display = 'none';
            document.getElementById('pagination').style.display = 'none';
        }
        document.getElementById('searchBtn').addEventListener('click', function() {
            bookName = document.getElementById('bookNameSearch').value.trim();
            currentPage = 1;
            loadOrders();
        });
        document.getElementById('resetBtn').addEventListener('click', function() {
            document.getElementById('bookNameSearch').value = '';
            bookName = '';
            currentPage = 1;
            loadOrders();
        });
        document.getElementById('bookNameSearch').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('searchBtn').click();
            }
        });
        // 订单详情弹窗
        window.viewOrder = function(orderId) {
            const mask = document.getElementById('orderModalMask');
            const content = document.getElementById('orderModalContent');
            content.innerHTML = '<div style="text-align:center;color:#888;">加载中...</div>';
            mask.style.display = 'flex';
            fetch(`${apiBaseUrl}/bookOrder/${orderId}`)
                .then(res => res.json())
                .then(data => {
                    if (data.success && data.code === 200) {
                        const order = data.data;
                        let statusText = getStatusText(order.status);
                        let statusClass = getStatusClass(order.status);
                        let createdAt = formatDate(order.createdAt);
                        let timeRow = '';
                        let timeLabel = '';
                        if (order.status === 1) {
                            timeLabel = '发货时间';
                            timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                        } else if (order.status === 2) {
                            timeLabel = '签收时间';
                            timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                        } else if (order.status === 3) {
                            timeLabel = '取消时间';
                            timeRow = `<div class=\"modal-row\"><span class=\"modal-label\">${timeLabel}：</span><span class=\"modal-value\">${formatDate(order.updatedAt)}</span></div>`;
                        }
                        let statusTagClass = 'modal-status-tag';
                        if (statusClass === 'shipped') statusTagClass += ' shipped';
                        if (statusClass === 'completed') statusTagClass += ' completed';
                        if (statusClass === 'cancelled') statusTagClass += ' cancelled';
                        content.innerHTML = `
                            <div class=\"modal-row\"><span class=\"modal-label\">订单ID：</span><span class=\"modal-value\"><strong>${order.id}</strong></span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">书名：</span><span class=\"modal-value\">${order.bookTitle}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">商家：</span><span class=\"modal-value\">${order.merchantName || ''}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">数量：</span><span class=\"modal-value\">${order.quantity}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">总价：</span><span class=\"modal-value\"><strong>￥${order.totalPrice.toFixed(2)}</strong></span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">订单状态：</span><span class=\"modal-value\"><span class=\"${statusTagClass}\">${statusText}</span></span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">下单时间：</span><span class=\"modal-value\">${createdAt}</span></div>
                            ${timeRow}
                        `;
                    } else {
                        content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">加载失败: '+(data.message||'未知错误')+'</div>';
                    }
                })
                .catch(() => {
                    content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">网络错误，无法加载订单详情</div>';
                });
        };
        document.getElementById('orderModalClose').onclick = function() {
            document.getElementById('orderModalMask').style.display = 'none';
        };
        document.getElementById('orderModalMask').onclick = function(e) {
            if (e.target === this) this.style.display = 'none';
        };
        // 取消订单功能
        window.cancelOrder = function(orderId) {
            if (!confirm('确定要取消该订单吗？')) return;
            fetch(`${apiBaseUrl}/bookOrder`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: orderId, status: 3 })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('订单已取消！');
                    loadOrders();
                } else {
                    alert(data.message || '取消失败');
                }
            })
            .catch(() => {
                alert('网络错误，取消失败');
            });
        };
        // 签收订单功能
        window.signOrder = function(orderId) {
            if (!confirm('确定要签收该订单吗？')) return;
            fetch(`${apiBaseUrl}/bookOrder`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: orderId, status: 2 })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('订单已签收！');
                    loadOrders();
                } else {
                    alert(data.message || '签收失败');
                }
            })
            .catch(() => {
                alert('网络错误，签收失败');
            });
        };
        // 初始加载
        loadOrders();
        // 每30秒自动刷新
        var orderAutoRefreshTimer = setInterval(loadOrders, 30000);
        window.addEventListener('beforeunload', function() { clearInterval(orderAutoRefreshTimer); });
        // 退出登录
        document.getElementById('logoutBtn').onclick = function() {
            localStorage.removeItem('userInfo');
            window.location.href = 'login.html';
        };
    })();
    </script>
</body>
</html> 